package org.apache.pdfbox.arktaohtml.slide;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.arktaohtml.Config;
import org.apache.pdfbox.arktaohtml.Utils.Utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

@Slf4j
public class AUtils {
    public static double pt2px(double pt) {

        return pt * 4 / 3;
    }

    public static double px2pt(double pt) {

        return pt * 3 / 4;
    }

    /**
     * 将 BufferedImage 转为图片，并返回HTML中可用的图片地址
     *
     * @param bimg
     * @return String 图片的网页地址， 如 http://192.168.1.102/a.png
     */
    public static String getImageUrlFromBufferedImage(BufferedImage bimg) {

        return getImageWebSrcByAbsoultSrc(getImageAbsPathFromBufferImage(bimg));
    }

    /**
     * 保持 BufferedImage
     *
     * @param bimg
     * @return String 图片的觉得存储路径， 如 d://a.png
     */
    public static String getImageAbsPathFromBufferImage(BufferedImage bimg) {
        String fileSaveName;
        try {
            String savePath = Config.IMAGE_TRANSTEMPSAVE_PATH + File.separator;
            File folder = new File(savePath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            fileSaveName = savePath + Utils.getRandomStr(32).toLowerCase() + ".png";
            FileOutputStream out = new FileOutputStream(fileSaveName);
            javax.imageio.ImageIO.write(bimg, "png", out);
            out.close();
            return fileSaveName;
        } catch (Exception e) {
            log.error("Trans BufferImage to png error", e);
            return null;
        }

    }

    /**
     * 根据图片的绝对路径，获取其网页的访问地址
     *
     * @param imageSrc 图片的绝对路径
     * @return String 图片的访问地址，如 http://192.168.1.102/a.png
     */
    public static String getImageWebSrcByAbsoultSrc(String imageSrc) {
        File f = new File(imageSrc);
        if (!f.exists()) {
            return "";
        }

        if (Config.DEBUG) {
            return Config.IMAGE_TEST_WEBSERVER + "/img/" + f.getName();
        } else {
            return Config.IMAGE_PRODUCT_WEBSERVER + "/" + imageSrc.substring(imageSrc.lastIndexOf("/") + 1);
        }
    }
}
